<template>
  <el-container class="home-container">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '240px'">
      <div class="logo">
        <img src="../assets/img/logo2.png"
             class="logo_icon" />
        <p class="logo_text"
           :style="{ width: isCollapse ? '0' : '120px' }">
          智慧社区管理系统
        </p>
      </div>
      <!-- 侧边栏菜单区域 -->
      <el-menu :default-active="activePath"
               background-color="#333744"
               text-color="#fff"
               active-text-color="#ffd04b"
               unique-opened
               :collapse="isCollapse"
               :collapse-transition="false"
               router
               class="left_menu">
        <SubMenu :list="menuList"></SubMenu>
      </el-menu>
    </el-aside>

    <!-- 页面主体区域 -->
    <el-container>
      <!-- 头部区域 -->
      <el-header class="header">
        <!-- 头部信息 -->
        <div class="header_top">
          <div class="header_left">
            <!-- 侧边栏展开和收缩图标 -->
            <div class="icon_div"
                 @click="toggleCollapse">
              <i class="el-icon-s-fold"></i>
            </div>
            <div class="icon_div">
              <FullScreen />
            </div>
            <!-- 刷新按钮 -->
            <div class="icon_div"
                 @click="reload">
              <i class="el-icon-refresh"></i>
            </div>
            <!-- 当前所在的路由 -->
            <!-- <div class="bread_crumb">{{activeTitle}}</div> -->
          </div>
          <div class="header_right">
            <el-dropdown @command="userTools">
              <div class="user_right">
                <!-- 头像 -->
                <div class="user_img">
                  <img src="../assets/img/user_img.png"
                       alt />
                </div>
                <!-- 用户名 -->
                <div class="user_info">
                  <span>{{userInfo.name}} | </span>
                  <span>{{userInfo.name=='admin'?'平台管理员':(userInfo.name=='19979228261'?'社区管理员':'物业管理员')}}</span>
                </div>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item class="dropdown_item"
                                  command="personal">
                  <i class="iconfont">&#xe8c9;</i> 个人中心
                </el-dropdown-item>
                <!-- <el-dropdown-item
                  class="dropdown_item"
                  command="updatePassword"
                >
                  <i class="el-icon-edit-outline"></i> 修改密码
                </el-dropdown-item> -->
                <el-dropdown-item class="dropdown_item"
                                  command="logout">
                  <i class="iconfont">&#xe65f;</i> 退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
        <div class="header_bottom">
          <div class="bottom_tab">
            <el-tabs v-model="activePath"
                     type="card"
                     @tab-click="clickTab">
              <el-tab-pane v-for="(item, index) in tabList"
                           :key="item.name"
                           :label="item.title"
                           :name="item.url">
                <div slot="label"
                     class="tabs_info"
                     v-if="index == 0">
                  {{ item.title }}
                </div>
                <div slot="label"
                     class="tabs_info"
                     v-else>
                  {{ item.title }}
                  <div class="tabs_info_icon">
                    <i class="el-icon-circle-close"
                       @click.stop="coloseTab(item)"></i>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
          <div class="bottom_tool">
            <el-dropdown class="tab_tools"
                         @command="tabTools">
              <div class="tools_open">
                <i class="el-icon-arrow-down"></i>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item class="tools_item"
                                  command="left">关闭左侧</el-dropdown-item>
                <el-dropdown-item class="tools_item"
                                  command="right">关闭右侧</el-dropdown-item>
                <el-dropdown-item class="tools_item"
                                  command="other">关闭其他</el-dropdown-item>
                <el-dropdown-item class="tools_item"
                                  command="all">关闭全部</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      <el-main class="main">
        <keep-alive :include="KeepAlive">
          <router-view />
        </keep-alive>
      </el-main>
    </el-container>
    <!-- 修改密码 -->
    <el-dialog title="修改密码"
               :visible.sync="editDialogVisible"
               width="50%"
               @close="editDialogClosed">
      <el-form ref="editFormRef"
               :model="editForm"
               label-width="100px"
               :rules="editFormules">
        <el-form-item label="原密码"
                      prop="password1">
          <el-input v-model="editForm.password1"></el-input>
        </el-form-item>
        <el-form-item label="新密码"
                      prop="password2">
          <el-input v-model="editForm.password2"></el-input>
        </el-form-item>
        <el-form-item label="确认密码"
                      prop="password3">
          <el-input v-model="editForm.password3"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editPasswordInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 个人中心页面 -->
    <el-dialog title="个人中心"
               :visible.sync="centerDialogVisible"
               width="50%"
               @close="centerDialogClosed">
      <el-form :model="addForm"
               :rules="addFormRules"
               ref="addFormRef"
               label-width="80px">
        <el-form-item label="账号"
                      prop="name">
          <el-input v-model="addForm.name"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="addForm.password"
                    show-password></el-input>
        </el-form-item>
        <el-form-item label="状态"
                      prop="status">
          <el-select v-model="addForm.status"
                     placeholder="请选择状态"
                     class="select">
            <el-option v-for="item in statusList"
                       :key="item.id"
                       :label="item.value"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editCenter">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>
<script>
import FullScreen from '../components/FullScreen'
import { menuList, commmunitymenuList, propertyList } from '../utils/menuList.js'
import SubMenu from '@/components/SubMenu'
import {
  mapState
} from 'vuex'
import screenfull from 'screenfull'
export default {
  components: {
    SubMenu,
    FullScreen,
  },
  data () {
    return {
      addForm: {
        name: '',
        password: '',
        status: ''
      },
      addFormRules: {},
      // 左侧菜单数据
      menuList: [],
      //过滤按钮节点后的左侧菜单数据
      filterMenuList: [],
      // 当前登录角色的按钮(包括启用和未启用)
      unFilterButtonList: [],
      // 当前登录角色的按钮（启用）
      buttonList: [],
      // 记录列表分页区的参数
      queryInfo: {
        //搜索条件
        query: "",
      },

      statusList: [
        { id: 0, value: '异常' },
        { id: 1, value: '正常' }
      ],
      // 默认初始不折叠
      isCollapse: false,
      clientHeight: '',
      editForm: {},
      // 控制修改对话框的显示与隐藏
      editDialogVisible: false,
      centerDialogVisible: false,
      editFormules: {},
    }
  },
  created () {
    this.getMenuList();
    this.getButtonList();
    // if (this.userInfo.name == 'admin') {   // 平台管理员
    //   this.menuList = menuList
    // } else if (this.userInfo.name == '19979228261') {   // 营养师、医生
    //   this.menuList = commmunitymenuList
    // } else if (this.userInfo.name == '18370428003') {   // 商家（医药代表）
    //   this.menuList = propertyList
    // }
  },
  computed: {
    // 在state中拿数据
    ...mapState({
      KeepAlive: (state) => state.KeepAlive, // keepalive缓存
      tabList: (state) => state.tabList, // tags菜单列表
      activeTitle: (state) => state.activeTitle, //面包屑导航名称
      userInfo: (state) => state.user.userInfo, //存储的用户数据
    }),
    //防止因为v-model双向绑定导致报错
    //已选中菜单
    activePath: {
      get () {
        return this.$store.state.activePath
      },
      set () { },
    },
  },
  methods: {
    // 动态获取当前登录角色(社区角色）的菜单权限列表
    async getMenuList () {
      var userInfo = window.sessionStorage.getItem("userInfo")
      var user_info = JSON.parse(userInfo)
      // var json = eval("(" + userInfo + ")");
      // console.log(json.id);

      var myRoleId = user_info.roles[0].communityRoleId
      var myCommunityId = user_info.roles[0].communityId
      // console.log(user_info.id);
      console.log(myRoleId)
      console.log(myCommunityId)
      // this.queryInfo.query = rowInfo.id
      // this.queryInfo.condition = `communityRoleId = ${myRoleId} && state= 1`
      // 调用接口获取当前社区角色的所有启用的菜单列表（不包含按钮）
      const { data: res } = await this.$http.post("SystemcommunityroleAction/getRoleOfSysMenuMap", { defineRoleId: myRoleId, communityId: myCommunityId })
      // console.log("原数组")
      // console.log(res.rows)
      // console.log("原数组")
      this.menuList = res.rows
      console.log("menuList")
      console.log(this.menuList)
      console.log("menuList")
      // // 获取当前登录角色的按钮列表（启用和未启用）
      // this.getUnFilterButtonList()
      // // 获取当前登录角色的按钮列表（启用）
      // this.getButtonList()

      // 调用filterMenu方法过滤掉menuList中的所有unFilterButtonList
      // this.filterMenu(this.menuList,this.unFilterButtonList)




      // 获取的菜单列表（可能需要过滤掉按钮）直接作为menuList使用，渲染左侧导航栏菜单
      // this.menuList = res.rows
      //对获取的menuList树形数据进行过滤，删除所有的按钮节点：这里过滤了10次，每次删除一层按钮节点（主要页面增删改查几个按钮）
      this.menuList = res.rows
      for (var i = 0; i < 10; i++)
        this.menuList = this.filterNode(this.menuList);

      // this.menuList = this.filterNode(res.rows);
      // this.menuList = this.filterNode(this.menuList);
      // this.menuList = this.filterNode(this.menuList);
      // this.menuList = this.filterNode(this.menuList);
      // this.menuList = this.filterNode(this.menuList);
      // this.menuList = this.filterNode(this.menuList);
      console.log("过滤后菜单")
      console.log(this.menuList)
      console.log("过滤后菜单")

    },
    // 获得当前登录角色（社区）的按钮列表，并且放入缓存
    async getUnFilterButtonList () {
      // 获取当前登录角色（社区）角色id
      var myRoleId = sessionStorage.getItem("myRoleId")


      // 查询所有社区角色id为当前角色id的的按钮
      // this.queryInfo.condition = `communityRoleId="${myRoleId}" && state=1`
      this.queryInfo.condition = `communityRoleId=6 `
      const { data: res } = await this.$http.get("SystemcommunityrolemenuchildrenAction/getBasicInfos", { params: this.queryInfo })
      // 提取出数组中的menuButtonId项组成新数组
      var unFilterButtonList = res.rows.map((item, index) => {
        return item.menuButtonId
      })
      this.unFilterButtonList = unFilterButtonList
      // 将当前登录角色拥有操作权限的按钮数组放入缓存
      sessionStorage.setItem("unFilterButtonList", unFilterButtonList)
      console.log("unFilterButtonList")
      console.log(this.unFilterButtonList)
      console.log("unFilterButtonList")

      this.filterMenu(this.menuList, this.unFilterButtonList)

    },
    // 获得当前登录角色（社区）的启用按钮列表，并且放入缓存
    async getButtonList () {
      // 获取当前登录角色（社区）角色id
      var userInfo = window.sessionStorage.getItem("userInfo")
      var user_info = JSON.parse(userInfo)
      var myRoleId = user_info.roles[0].communityRoleId

      // 查询所有社区角色id为当前角色id的并且状态为启用的按钮
      // this.queryInfo.condition = `communityRoleId="${myRoleId}" && state=1`
      this.queryInfo.condition = `communityRoleId=${myRoleId} && state=1`
      const { data: res } = await this.$http.get("SystemcommunityrolemenuchildrenAction/getBasicInfos", { params: this.queryInfo })
      // 提取出数组中的menuButtonId项组成新数组
      var buttonList = res.rows.map((item, index) => {
        return item.menuButtonId
      })
      this.buttonList = buttonList
      // 将当前登录角色拥有操作权限的按钮数组放入缓存
      sessionStorage.setItem("myButtonList", this.buttonList)

      console.log("myButtonList")
      console.log(this.buttonList)
      console.log("myButtonList")

    },
    //封装js方法，对树形数据做过滤按钮节点处理
    deleteNode (arr) {
      console.log("arr是")
      console.log(arr)
      for (var i = 0; i <= arr.length; i++) {
        const node = arr[i];
        console.log("node是")
        console.log(node)
        // if (node.id > 1000) {
        //   arr.splice(i, 1);
        // }
        if (!node.id > 1000) {
          console.log("删除")
          arr.splice(i, 1);
        }
        // 判断children存在并且有数据
        if (node.childrens != null) {
          this.deleteNode(node.childrens);
        }
      }
      console.log("ok")
      console.log(arr)
      console.log("ok")
      return arr
    },
    // 过滤方法2:该过滤方法只能过滤一个节点，因为删除第一个节点改变了树形数据的结构，索引改变导致第二个节点无法删除（多次调用，每次删除一层节点）
    filterNode (arr) {
      arr.map((item, index) => {
        if (item.id > 1000) {
          arr.splice(index, 1)
        }
        if (item.childrens) {
          this.filterNode(item.childrens)
        }
      })
      return arr
    },
    // 过滤方法3
    filterMenu (menuList, buttonList) {
      this.filterMenuList = menuList.filter(item => {
        // console.log(item.id)
        // return buttonList.indexOf(item.id) > -1
        if (buttonList.indexOf(item.id) > -1) {
          console.log(item.id)
          return buttonList.indexOf(item.id)
        }
      }).map(item => {
        item = Object.assign({}, item)
        if (item.childrens) {
          item.childrens = filterMenu(item.childrens, buttonList)
        }
        return item
      })
    },



    // 点击按钮，切换侧边栏的折叠与展开
    toggleCollapse () {
      this.isCollapse = !this.isCollapse
    },

    reload () {
      this.$router.replace('/refresh');
      console.log('刷新')
    },

    //点击tab标签
    clickTab (item) {
      // console.log('点击')
      let oldPath = this.$store.activePath //获取之前选中的路由
      //判断点击的是不是同一个tab
      if (item.name === oldPath) {
        return
      }
      //不是同一个tab，更新state并且跳转路由
      this.$store.commit('clickTab', item.name)
      this.$router.push(item.name)
    },
    //关闭tab标签
    coloseTab (item) {
      let name = item.name
      let router = this.$router
      // 把路由也传递给mutations，然后在mutations直接跳转路由
      this.$store.commit('closeTab', {
        name,
        router
      })
    },
    // tab标签工具
    tabTools (type) {
      let router = this.$router
      switch (type) {
        case 'left':
          this.$store.commit('tabTools', 'left')
          break
        case 'right':
          this.$store.commit('tabTools', 'right')
          break
        case 'other':
          this.$store.commit('tabTools', 'other')
          break
        case 'all':
          this.$store.commit('closeAll', {
            router
          })
          break
      }
    },
    //点击用户的下拉菜单
    userTools (type) {
      switch (type) {
        case 'personal':
          this.centerDialogVisible = true;
          this.getInfo(this.userInfo.id)
          break;
        case 'logout':
          this.$store.commit('logout');
          window.sessionStorage.clear()
          this.$router.push('/login')
          break;
        case 'updatePassword':
          this.editDialogVisible = true;
          break;
      }
    },
    // 监听修改街道办对话框的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 监听个人中心对话框的关闭事件
    centerDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    //点击确定修改密码
    editPasswordInfo () {

    },
    //修改个人中心信息
    async editCenter () {
      delete this.addForm.roles
      const { data: res } = await this.$http.post("SystemuserAction/updateNoNull", this.addForm)
      if (!res.success) return this.$message.error('更新信息失败！')
      // 关闭对话框
      this.centerDialogVisible = false
      // 提示修改成功
      this.$message.success('更新信息成功！')
    },
    async getInfo (id) {
      const { data: res } = await this.$http.post("SystemuserAction/getObjectById", { id })
      if (!res.success)
        return this.$message.error('获取信息失败')
      this.addForm = res.rows[0]
      console.log(this.addForm);
    }
  }
}

</script>
<style scoped>
.el-container {
  height: 100%;
}

.el-header {
  /* // background-color: #373d41; */
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* color: #fff; */
  font-size: 20px;
}

/* // >div {
  //   display: flex;
  //   align-items: center; */

.logo_icon {
  width: 40px;
  height: 43.7px;
}

span {
  margin-left: 15px;
}

/* 头像区域 */
.header_right {
  height: 100%;
}

.el-dropdown {
  height: 100%;
  padding: 0 10px;
}

.el-dropdown:hover {
  background-color: #f6f7f9;
}

.dropdown_item {
  font-size: 13px;
}

.dropdown_item > i {
  font-size: 13px;
}

.user_right {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-aside {
  background-color: #333744;
}

.el-menu {
  border-right: none;
}

.left_menu {
  height: calc(100% - 84px);
  overflow-y: auto;
  border-right: 0 !important;
}

/* 侧边菜单栏不显示滚动条 */
.left_menu::-webkit-scrollbar {
  width: 0;
}

/* // 隐藏element-ui垂直滚动条 */
.el-main::-webkit-scrollbar {
  width: 0;
}

.el-main {
  padding: 10px;
}

.bottom_tab {
  width: 96%;
}

.bottom_tool {
  width: 4%;
  height: 100%;
}

/* // background-color: #eaedf1;
  // } */

/*每个tab标签的样式*/
.el-tabs /deep/ .el-tabs__item {
  border-left: 0 !important;
  border-bottom: 0 !important;
  background-color: #fff;
  border-radius: 3px;
  margin-right: 6px;
  padding: 0 10px;
  height: 32px;
  line-height: 32px;
  color: #808695;
  font-size: 13px;
  box-sizing: border-box;
}

.el-tabs__content {
  display: none !important;
}

.el-tabs /deep/ .el-tabs__header {
  border-bottom: 0 !important;
  margin: 0 !important;
}

.el-tabs /deep/ .el-tabs__header .el-tabs__nav {
  border: 0 !important;
}

.el-tabs /deep/ .el-tabs__item:last-child {
  padding-right: 10px !important;
}

.el-tabs /deep/ .el-tabs__item:nth-child(2) {
  padding-left: 10px !important;
}

.tabs_info {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.tabs_info_icon {
  height: 15px;
  width: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  margin-left: 5px;
  transition: all 0.3s;
  z-index: 12;
}

.tabs_info_icon:hover {
  background-color: #dddd;
}

/* 选中的样式 */
.el-tabs /deep/ .el-tabs__item.is-active {
  color: #409eff;
  border: 1px solid #409eff !important;
}

/* 标签的关闭图标 */
.tabs_icon {
  line-height: 15px;
  font-size: 12px;
  /* border-radius: 50%; */
  /* transition: all 0.3s ease-in-out; */
}

/* tab标签页的左右箭头 */
.el-tabs /deep/ .el-tabs__nav-next,
.el-tabs /deep/ .el-tabs__nav-prev {
  line-height: 32px;
  color: #808695;
}

.toggle_button {
  background-color: #4a5064;
  color: #fff;
  font-size: 10px;
  line-height: 24px;
  text-align: center;
  letter-spacing: 0.2em;
  cursor: pointer;
}

.tab_tools {
  width: 30px;
  height: 30px;
  background-color: #fff;
  padding: 0;
}

.tools_open {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tools_item {
  font-size: 13px;
  line-height: 20px;
  padding: 2px 15px;
  color: #808695;
}

.el-menu /deep/.el-menu--inline {
  padding-left: 10px;
}

/** 新增代码 */
.header {
  height: 108px !important;
  padding: 0 !important;
  flex-direction: column;
  /* box-shadow: 0 1px 1px 0px #dddddd; */
}

.header_top {
  width: 100%;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* padding: 0 20px; */
  box-sizing: border-box;
}

.header_bottom {
  width: 100%;
  height: 50px;
  background-color: #f6f7f9;
  padding: 10px 10px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header_right {
  height: 100%;
  padding-right: 20px;
  cursor: pointer;
}

.el-dropdown {
  height: 100%;
  padding: 0 10px;
}

.el-dropdown:hover {
  background-color: #f6f7f9;
}

.dropdown-menu {
  margin-top: 5px !important;
}

.dropdown_item {
  font-size: 13px;
}

.dropdown_item > i {
  font-size: 13px;
}

.user_right {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.user_img {
  width: 35px;
  height: 35px;
}

.user_img > img {
  width: 100%;
  height: 100%;
}

.user_info {
  padding-left: 10px;
  font-size: 13px;
}

.header_left {
  height: 100%;
  display: flex;
  color: #555555;
}

.icon_div {
  height: 100%;
  width: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.icon_div:hover {
  background-color: #f6f7f9;
  transition: all 0.3s;
}

.full-screen-wrapper {
  height: 25px;
  margin-right: 0;
  margin: 0 10px;
}

.logo {
  /* width: 100%; */
  display: flex;
  height: 40px;
  line-height: 40px;
  align-items: center;
  margin: 15px 0 10px 15px;
}

.logo_icon {
  width: 40px;
  height: 40px;
}

.logo_text {
  margin-left: 10px;
  height: 100%;
  color: #babbbd;
  font-size: 15px;
  overflow: hidden;
  transition: width 0.3s ease-in-out;
}

/* 内容区域 */
.main {
  background-color: #f6f7f9;
  padding: 0;
}
.select {
  width: 100%;
}
</style>
